import { NzModalService } from 'ng-zorro-antd/modal';
import { BirefApiService } from './../../../api/biref-api.service';
import { Brief, BriefParam } from './../../../model/brief';
import { NzMessageService } from 'ng-zorro-antd/message';
import { PhasedTaskApiService } from './../../../api/phased-task-api.service';
import { BriefAdderComponent } from './../../../common-util/brief-adder/brief-adder.component';
import { PhaseTaskAdderComponent } from './../phase-task-adder/phase-task-adder.component';
import { NzTreeNodeOptions } from 'ng-zorro-antd/tree';
import { PhasedTask, PhasedTaskParam, PhasedTaskWithChildren, ProcessStatus } from './../../../model/task';
import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-phase-task-detail',
  templateUrl: './phase-task-detail.component.html',
  styleUrls: ['./phase-task-detail.component.less']
})
export class PhaseTaskDetailComponent implements OnInit {

  taskDetail: PhasedTask = new PhasedTask(new PhasedTaskParam());
  treeView: NzTreeNodeOptions[] = [];
  isTaskModalVisible = false;
  isTaskBriefVisible = false;
  taskSelectNode: Array<NzTreeNodeOptions> = [];
  taskTags = [];
  briefList: Array<Brief> = [];
  @ViewChild('taskAdder') taskAdder?: PhaseTaskAdderComponent;
  @ViewChild('briefAdder') briefAdder?: BriefAdderComponent;
  briefModalTitle = '添加简报';

  constructor(
    private route: ActivatedRoute,
    private taskApi: PhasedTaskApiService,
    private message: NzMessageService,
    private briefApi: BirefApiService,
    private modal: NzModalService,
    private router: Router,
  ) { }

  ngOnInit(): void {
    this.fetchTaskSelectNode();
    this.route.data.subscribe(
      data => {
        this.taskDetail = data.task;
        this.treeView = [data.treeView];
        this.taskTags = data.task.tags.split(',');
        this.fetchBrief(this.taskDetail.id);
        if (this.taskTags[0] === '') {
          this.taskTags = [];
        }
      }
    );
  }

  editTask(): void {
    this.taskAdder?.setData(this.taskDetail);
    this.isTaskModalVisible = true;
  }

  addBiref(): void {
    this.briefModalTitle = '添加简报';
    this.isTaskBriefVisible = true;
    this.briefAdder?.setPhaseTaskId(this.taskDetail.id);
  }

  briefDeleteConfirm(briefId: number | undefined): void {
    if (briefId) {
      this.briefApi.delete([briefId]).subscribe(
        (response: Array<Brief>) => {
          if (response && response.length > 0) {
            response.forEach(
              (item: Brief) => this.briefList = this.briefList.filter(briefItem => briefItem.id !== item.id)
            );
          }
          this.message.success('删除简报成功');
        },
        err => {
          this.message.error('删除简报错误');
          console.error(err);
        }
      );
    }

  }
  briefDeleteCancel(): void {

  }
  briefEditShow(briefItem: any): void {
    this.briefModalTitle = '编辑简报';
    this.isTaskBriefVisible = true;
    this.briefAdder?.setValue(briefItem);
    this.briefAdder?.setPhaseTaskId(this.taskDetail.id);

  }

  handleBriefCancel = (): void => {
    this.briefAdder?.reset();
    this.isTaskBriefVisible = false;
  }

  handleBriefOk(): void {
    const briefData = this.briefAdder?.getValue();
    console.log(briefData);
    if (briefData) {
      if (briefData.id) {
        this.editBrief(briefData);
      } else {
        this.createBrief(briefData);
      }
    }
  }

  handleAdderCancel = (): void => {
    this.taskAdder?.reset();
    this.isTaskModalVisible = false;
  }
  handleAdderOk(): void {
    const data = this.taskAdder?.getData();
    if (data) {
      this.taskApi.update(this.taskDetail.id, data).subscribe(
        task => {
          this.taskDetail = new PhasedTask(task);
          this.taskTags = task.tags.split(',');
          this.fetchTaskSelectNode();
          this.message.success('修改工作信息成功');
          this.reflashTreeView();
          setTimeout(this.handleAdderCancel, 500);
        },
        err => {
          this.message.error('修改工作信息错误');
          console.error(err);
        }
      );
    }
  }

  completeTask(): void {
    this.modal.confirm({
      nzTitle: '确定完成该工作?',
      nzContent: '完成该工作及其子工作。',
      nzOnOk: () => {
        this.taskApi.updateTaskProcessStatus(this.taskDetail.id, ProcessStatus.done).toPromise().then(
          param => {
            this.taskDetail = new PhasedTask(param);
            this.fetchBrief(this.taskDetail.id);
          }
        );
      }
    });
   }
  deleteTask(): void {
    this.modal.confirm({
      nzTitle: '确定删除该工作?',
      nzContent: '删除该工作及其子工作。',
      nzOnOk: () => {
        this.taskApi.delete([this.taskDetail.id]).toPromise().then(
          param => {
            this.router.navigateByUrl('/phaseTask/overview');
          }
        );
      }
    });
  }

  private createBrief(brief: BriefParam): void {
    this.briefApi.create(brief).subscribe(
      briefResponse => {
        this.message.success('添加简报成功');
        this.briefList = [briefResponse, ...this.briefList];
        setTimeout(this.handleBriefCancel, 500);
      },
      err => {
        this.message.success('添加简报错误');
        console.error(err);
      }
    );
  }

  private editBrief(briefData: BriefParam): void {

    this.briefApi.update(briefData.id!, briefData).subscribe(
      briefItem => {
        this.message.success('编辑简报成功');
        this.fetchBrief(this.taskDetail.id);
        setTimeout(this.handleBriefCancel, 500);

      },
      err => {
        console.log(err);
        this.message.success('编辑简报错误');
      }
    );
  }

  private fetchTaskSelectNode(): void {
    this.taskApi.listWithChildren().subscribe(
      tasks => {
        this.taskSelectNode = tasks.map(param => new PhasedTaskWithChildren(param).convertToNzTreeNodeOption());
      },
      err => {
        this.message.error('获取工作菜单错误');
        console.error(err);
      }
    );
  }

  private reflashTreeView(): void {
    this.taskApi.listTreeView(this.taskDetail.id).subscribe(
      tree => (this.treeView = [tree])
    );
  }

  private fetchBrief(taskid: number): void {
    this.briefApi.getListByPhaseTaskId(taskid).subscribe(
      briefs => {
        this.briefList = briefs;
      },
      err => {
        this.message.error('获取工作简报错误!');
        console.error(err);

      }
    );
  }
}
